package com.mvd.app.upload;

import android.annotation.TargetApi;
import android.app.Service;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.media.MediaMetadataRetriever;
import android.os.Build;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.text.TextUtils;

import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.base.Request;
import com.mvd.app.api.ApiConfig;
import com.mvd.app.application.BaseApplication;
import com.mvd.app.application.UploadEvent;
import com.mvd.app.commons.PDALogUtils;
import com.mvd.app.commons.SharedPreferencesUtils;
import com.mvd.app.commons.UtilsLog;
import com.mvd.app.model.VideoUploadModel;
import com.vincent.videocompressor.VideoCompress;
import com.zolad.videoslimmer.VideoSlimmer;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @ProjectName: PDA_38900_guizhou
 * @Package: com.mvd.app.upload
 * @ClassName: MyUploadService
 * @Description: java类作用描述
 * @Author: liuxj
 * @CreateDate: 2020-11-02 15:42
 * @UpdateUser: 更新者
 * @UpdateDate: 2020-11-02 15:42
 * @UpdateRemark: 更新说明
 * @Version: 1.0
 */
public class MyUploadService extends Service implements ApiConfig {
    private long startTime, endTime;
    private String currentOutputVideoPath = "";//压缩后的视频地址

    private String videoTime = "";//获取视频时长
    private int videoWidth = 0;//获取视频的宽度
    private int videoHeight = 0;//获取视频的高度
    private int videoGotation = 0;//获取视频的角度
    private Bitmap mBitMap;
    private Double videoLength = 0.00;//视频时长 s

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        UtilsLog.e("MyService.onBind------------");
        return null;
    }

    @Override
    public void onCreate() {
        UtilsLog.e("MyService.onCreate------------");
        EventBus.getDefault().register(this);
        super.onCreate();
    }

    @Subscribe(threadMode = ThreadMode.ASYNC)
    public void getUploadEventBus(UploadEvent event) {
        UtilsLog.e("MyUploadService===" + event.getMessage());
        UtilsLog.e("MyUploadService===" + event.getPath());
//        filePath = event.getMessage();
//        filePath2 = event.getPath();
//        if (event != null) {
////            getDataUploadPhoto(new File(event.getMessage()));
//            new Thread(new Runnable() {
//                @Override
//                public void run() {
//                    Message msg = new Message();
////                    msg.obj = event.getMessage();
//                    msg.arg1 = 1;
//                    handler_main.sendMessage(msg);
//                }
//            }).start();
//        }
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        UtilsLog.e("MyService.onStartCommand------------");
        if (intent != null) {
//            String data=intent.getStringExtra("service_data");
//            UserAccountModel model= (UserAccountModel) intent.getSerializableExtra("service_user_model");
//            UtilsLog.e("MyService.onStartCommand--------data----"+data);
//            UtilsLog.e("MyService.onStartCommand--------UserAccountModel----"+model.toString());
            VideoUploadModel model = (VideoUploadModel) intent.getSerializableExtra("service_model");
            UtilsLog.e("MyService.onStartCommand--------VideoUploadModel----" + model.toString());

//            videoCompress(model.getSize(), model.getZp(),model);
//            getDataUploadVideo(model);

            String quality = SharedPreferencesUtils.getVideoQuality(this);
            UtilsLog.e("MyUploadService---视频画质==" + quality);

            videoCompress_no(model);
//            if (quality.equals("低")) {
//                videoCompress_low(model.getSize(), model.getZp(), model);
//            } else if (quality.equals("中")) {
//                videoCompress_medium(model.getSize(), model.getZp(), model);
//            } else if (quality.equals("高")) {
//                videoCompress_high(model.getSize(), model.getZp(), model);
//            } else if (quality.equals("无")) {
////                videoCompress_no(model);
//                videoCompress(model.getSize(), model.getZp(), model);
//            } else {
////                startCompress(model);
//            }
        }
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        UtilsLog.e("MyService.onDestroy------------");
        super.onDestroy();
    }

    @Override
    public boolean onUnbind(Intent intent) {
        UtilsLog.e("MyService.onUnbind------------");
        EventBus.getDefault().unregister(this);
        return super.onUnbind(intent);
    }

    void videoCompress(String videoUriString, String videoPath, final VideoUploadModel model) {
        String logStr = "MyUploadService---videoCompress---压缩等级：无";
        PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStr.getBytes());
        VideoSlimmer.convertVideo(videoUriString, videoPath, 480, 800, 200 * 360 * 30, new VideoSlimmer.ProgressListener() {
            @Override
            public void onStart() {
                String logStr = "MyUploadService---videoCompress---压缩等级：无------onStart()";
                PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStr.getBytes());
            }

            @Override
            public void onFinish(boolean result) {
                String logStr = "MyUploadService---videoCompress---压缩等级：无------onFinish()";
                PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStr.getBytes());
                UtilsLog.e("videoCompress---视频路径=onFinish=" + result);
//                //convert finish,result(true is success,false is fail)
                getDataUploadVideo(model, false, "");
            }

            @Override
            public void onProgress(float percent) {
                UtilsLog.e("videoCompress---视频路径=onProgress=" + percent);
            }
        });
    }

    void videoCompress_medium(String videoUriString, String videoPath, final VideoUploadModel model) {
//        String destPath = tv_output.getText().toString() + File.separator + "VID_" + new SimpleDateFormat("yyyyMMdd_HHmmss", getLocale()).format(new Date()) + ".mp4";
        String logStr = "MyUploadService---videoCompress---压缩等级：中";
        PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStr.getBytes());
        VideoCompress.compressVideoMedium(videoUriString, videoPath, new VideoCompress.CompressListener() {
            @Override
            public void onStart() {
                String logStr = "MyUploadService---videoCompress---压缩等级：中------onStart()";
                PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStr.getBytes());
                String str = "Compressing..." + "\n"
                        + "Start at: " + new SimpleDateFormat("HH:mm:ss", getLocale()).format(new Date())
                        + "\n" + model.toString();
                UtilsLog.e("onStart==" + str);
                PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, str.getBytes());
                startTime = System.currentTimeMillis();
                Util.writeFile(BaseApplication.getSelf(), "Start at: " + new SimpleDateFormat("HH:mm:ss", getLocale()).format(new Date()) + "\n");
            }

            @Override
            public void onSuccess() {
                String logStr = "MyUploadService---videoCompress---压缩等级：中------onSuccess()";
                PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStr.getBytes());
                String str = "\n"
                        + "Compress Success!" + "\n"
                        + "End at: " + new SimpleDateFormat("HH:mm:ss", getLocale()).format(new Date()) + "\n" + model.toString();
                UtilsLog.e("onSuccess==" + str);
                PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, str.getBytes());
                endTime = System.currentTimeMillis();
                Util.writeFile(BaseApplication.getSelf(), "End at: " + new SimpleDateFormat("HH:mm:ss", getLocale()).format(new Date()) + "\n");
                Util.writeFile(BaseApplication.getSelf(), "Total: " + ((endTime - startTime) / 1000) + "s" + "\n");
                Util.writeFile(BaseApplication.getSelf());
                getDataUploadVideo(model, true, "");
            }

            @Override
            public void onFail() {
                String logStr = "MyUploadService---videoCompress---压缩等级：中------onFail()";
                PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStr.getBytes());
                UtilsLog.e("onFail==Compress Failed!" + new SimpleDateFormat("HH:mm:ss", getLocale()).format(new Date()));
                String str = "onFail==Compress Failed!" + new SimpleDateFormat("HH:mm:ss", getLocale()).format(new Date());
                endTime = System.currentTimeMillis();
                PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, str.getBytes());
                Util.writeFile(BaseApplication.getSelf(), "Failed Compress!!!" + new SimpleDateFormat("HH:mm:ss", getLocale()).format(new Date()));
            }

            @Override
            public void onProgress(float percent) {
                String str = "视频上传进度==" + String.valueOf(percent) + "%" + "\n" + model.toString() + "\n";
                PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, str.getBytes());
                UtilsLog.e("onProgress====" + str);
                model.setProgress(percent);
//                EventBus.getDefault().post(model);
            }
        });
    }

    void videoCompress_high(String videoUriString, String videoPath, final VideoUploadModel model) {
//        String destPath = tv_output.getText().toString() + File.separator + "VID_" + new SimpleDateFormat("yyyyMMdd_HHmmss", getLocale()).format(new Date()) + ".mp4";
        String logStr = "MyUploadService---videoCompress---压缩等级：高";
        PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStr.getBytes());
        VideoCompress.compressVideoHigh(videoUriString, videoPath, new VideoCompress.CompressListener() {
            @Override
            public void onStart() {
                String logStr = "MyUploadService---videoCompress---压缩等级：高------onStart()";
                PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStr.getBytes());
                String str = "Compressing..." + "\n"
                        + "Start at: " + new SimpleDateFormat("HH:mm:ss", getLocale()).format(new Date())
                        + "\n" + model.toString();
                UtilsLog.e("onStart==" + str);
                PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, str.getBytes());
                startTime = System.currentTimeMillis();
                Util.writeFile(BaseApplication.getSelf(), "Start at: " + new SimpleDateFormat("HH:mm:ss", getLocale()).format(new Date()) + "\n");
            }

            @Override
            public void onSuccess() {
                String logStr = "MyUploadService---videoCompress---压缩等级：高------onSuccess()";
                PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStr.getBytes());
                String str = "\n"
                        + "Compress Success!" + "\n"
                        + "End at: " + new SimpleDateFormat("HH:mm:ss", getLocale()).format(new Date()) + "\n" + model.toString();
                UtilsLog.e("onSuccess==" + str);
                PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, str.getBytes());
                endTime = System.currentTimeMillis();
                Util.writeFile(BaseApplication.getSelf(), "End at: " + new SimpleDateFormat("HH:mm:ss", getLocale()).format(new Date()) + "\n");
                Util.writeFile(BaseApplication.getSelf(), "Total: " + ((endTime - startTime) / 1000) + "s" + "\n");
                Util.writeFile(BaseApplication.getSelf());
                getDataUploadVideo(model, true, "");
            }

            @Override
            public void onFail() {
                String logStr = "MyUploadService---videoCompress---压缩等级：高------onFail()";
                PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStr.getBytes());
                UtilsLog.e("onFail==Compress Failed!" + new SimpleDateFormat("HH:mm:ss", getLocale()).format(new Date()));
                String str = "onFail==Compress Failed!" + new SimpleDateFormat("HH:mm:ss", getLocale()).format(new Date());
                endTime = System.currentTimeMillis();
                PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, str.getBytes());
                Util.writeFile(BaseApplication.getSelf(), "Failed Compress!!!" + new SimpleDateFormat("HH:mm:ss", getLocale()).format(new Date()));
            }

            @Override
            public void onProgress(float percent) {
                String str = "视频上传进度==" + String.valueOf(percent) + "%" + "\n" + model.toString() + "\n";
                PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, str.getBytes());
                UtilsLog.e("onProgress====" + str);
                model.setProgress(percent);
//                EventBus.getDefault().post(model);
            }
        });
    }

    void videoCompress_no(VideoUploadModel model) {
        getDataUploadVideo(model, false, "");
    }

    void videoCompress_low(String videoUriString, String videoPath, final VideoUploadModel model) {
//        String destPath = tv_output.getText().toString() + File.separator + "VID_" + new SimpleDateFormat("yyyyMMdd_HHmmss", getLocale()).format(new Date()) + ".mp4";
        VideoCompress.compressVideoLow(videoUriString, videoPath, new VideoCompress.CompressListener() {
            @Override
            public void onStart() {
                String logStr = "MyUploadService---videoCompress---压缩等级：低------onStart()";
                PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStr.getBytes());
                String str = "Compressing..." + "\n"
                        + "Start at: " + new SimpleDateFormat("HH:mm:ss", getLocale()).format(new Date())
                        + "\n" + model.toString();
                UtilsLog.e("onStart==" + str);
                PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, str.getBytes());
                startTime = System.currentTimeMillis();
                Util.writeFile(BaseApplication.getSelf(), "Start at: " + new SimpleDateFormat("HH:mm:ss", getLocale()).format(new Date()) + "\n");
            }

            @Override
            public void onSuccess() {
                String logStr = "MyUploadService---videoCompress---压缩等级：低------onSuccess()";
                PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStr.getBytes());
                String str = "\n"
                        + "Compress Success!" + "\n"
                        + "End at: " + new SimpleDateFormat("HH:mm:ss", getLocale()).format(new Date()) + "\n" + model.toString();
                UtilsLog.e("onSuccess==" + str);
                PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, str.getBytes());
                endTime = System.currentTimeMillis();
                Util.writeFile(BaseApplication.getSelf(), "End at: " + new SimpleDateFormat("HH:mm:ss", getLocale()).format(new Date()) + "\n");
                Util.writeFile(BaseApplication.getSelf(), "Total: " + ((endTime - startTime) / 1000) + "s" + "\n");
                Util.writeFile(BaseApplication.getSelf());
                getDataUploadVideo(model, true, "");
            }

            @Override
            public void onFail() {
                String logStr = "MyUploadService---videoCompress---压缩等级：低------onFail()";
                PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStr.getBytes());
                UtilsLog.e("onFail==Compress Failed!" + new SimpleDateFormat("HH:mm:ss", getLocale()).format(new Date()));
                String str = "onFail==Compress Failed!" + new SimpleDateFormat("HH:mm:ss", getLocale()).format(new Date());
                endTime = System.currentTimeMillis();
                PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, str.getBytes());
                Util.writeFile(BaseApplication.getSelf(), "Failed Compress!!!" + new SimpleDateFormat("HH:mm:ss", getLocale()).format(new Date()));
            }

            @Override
            public void onProgress(float percent) {
                String str = "视频上传进度==" + String.valueOf(percent) + "%" + "\n" + model.toString() + "\n";
                PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, str.getBytes());
                UtilsLog.e("onProgress====" + str);
                model.setProgress(percent);
//                EventBus.getDefault().post(model);
            }
        });
    }

    private Locale getLocale() {
        Configuration config = getResources().getConfiguration();
        Locale sysLocale = null;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            sysLocale = getSystemLocale(config);
        } else {
            sysLocale = getSystemLocaleLegacy(config);
        }

        return sysLocale;
    }

    @SuppressWarnings("deprecation")
    public static Locale getSystemLocaleLegacy(Configuration config) {
        return config.locale;
    }

    @TargetApi(Build.VERSION_CODES.N)
    public static Locale getSystemLocale(Configuration config) {
        return config.getLocales().get(0);
    }

    int upload_times = 0;//上传视频的次数

    //上传视频 is:是否压缩  true  是   false 否
    private void getDataUploadVideo(final VideoUploadModel carsInforModel, boolean is, String currentOutputVideoPath) {
        String logStr = "进入上传视频方法--MyUploadService--getDataUploadVideo------";
        PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStr.getBytes());
        String video_url_path = "";
        if (!TextUtils.isEmpty(currentOutputVideoPath)) {
            video_url_path = currentOutputVideoPath;
        } else {
            if (is) {
                video_url_path = carsInforModel.getZp();
            } else {
                video_url_path = carsInforModel.getSize();
            }
        }
        UtilsLog.e("MyUploadService---getDataUploadVideo==start==" + new SimpleDateFormat("HH:mm:ss", getLocale()).format(new Date()));
        UtilsLog.e("MyUploadService---上传视频---currentOutputVideoPath==" + currentOutputVideoPath);
        UtilsLog.e("MyUploadService---上传视频---carsInforModel==" + carsInforModel.toString());
        UtilsLog.e("MyUploadService---上传视频---url==" + carsInforModel.getPath());
        String pathLog = "视频真实上传路径====" + video_url_path;
        PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, pathLog.getBytes());
        OkGo.<String>post(carsInforModel.getPath())
                //次数
                .params("Times", carsInforModel.getTimes())
                //PlatformSN
                .params("PlatformSN", carsInforModel.getPlatformSN())
                .params("VideoType", carsInforModel.getVideoType())
                .params("ItemCode", carsInforModel.getItemCode())
                //车牌号码，两个拼起来的
                .params("CarNO", carsInforModel.getCarNO())
                //号牌类型
                .params("PlateType", carsInforModel.getPlateType())
                //外检车道，检测线代号
                .params("Line", carsInforModel.getLine())
                //车辆识别代码
                .params("VIN", carsInforModel.getVIN())
                //照片
                .params("zp", new File(video_url_path))
                //开始时间
                .params("StartTime", carsInforModel.getStartTime())
                //结束时间
                .params("EndTime", carsInforModel.getEndTime())
                .execute(new StringCallback() {
                    @Override
                    public void onStart(Request<String, ? extends Request> request) {
                        super.onStart(request);
//                        CommonUtils.showLoadingDialog(instances, "上传中...");
                    }

                    @Override
                    public void onSuccess(Response<String> response) {
//                        CommonUtils.hideLoadingDialog(instances);
                        String result = response.body();
                        UtilsLog.e("MyUploadService---上传视频-result==" + result);
                        String logStr = "\n" + "MyUploadService---外检上传视频--请求成功" +
                                "\n" + "URL::" + carsInforModel.getPath() + "\n" + "result:" + response.body() + "\n";
                        PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStr.getBytes());
                        if (!TextUtils.isEmpty(result) && !"[[]]".equals(result) && !"[{}]".equals(result)
                                && !"[]".equals(result)) {
                            String newResult = result.substring(1, result.length() - 1).replaceAll("\\\\",
                                    "");
                            UtilsLog.e("MyUploadService---上传视频-newResult==" + newResult);
                            if ("ok".equalsIgnoreCase(newResult)) {
                                UtilsLog.e("MyUploadService---上传视频-成功==");
                                carsInforModel.setStatement("1");
                                carsInforModel.save();
                            }
                        } else {
                            UtilsLog.e("MyUploadService---上传视频-result==" + "没有数据");
                        }

                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
//                        UpVideo_ok = false;
                        UtilsLog.e("MyUploadService---上传视频-onError==" + response.body());
                        UtilsLog.e("MyUploadService---上传视频-onError==" + response.getException());
                        String logStr = "\n" + "MyUploadService---上传录像视频-onError-失败" +
                                "\n" + "URL::" + carsInforModel.getPath() + "\n" + "result:" + response.body() + "\n" +
                                response.getException() + "\n" + response.message() + "\n";
                        PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStr.getBytes());
//                        CommonUtils.hideLoadingDialog(instances);
//                        Toast.makeText(instances, "上传录像失败，请重试", Toast.LENGTH_LONG).show();
                    }
                });
    }

    /**
     * 获取视频的时长
     */
    void getVideoTime(String mVideoPath) {
        try {
            MediaMetadataRetriever retr = new MediaMetadataRetriever();
            retr.setDataSource(mVideoPath);
            videoTime = retr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);//获取视频时长
            videoWidth = Integer.valueOf(retr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH));//获取视频的宽度
            videoHeight = Integer.valueOf(retr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT));//获取视频的高度
            videoGotation = Integer.valueOf(retr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_ROTATION));//获取视频的角度

            UtilsLog.e("MyUploadService---videoWidth=" + videoWidth);
            UtilsLog.e("MyUploadService---videoHeight=" + videoHeight);

//            MyLog.i(TAG, "videoTime=" + videoTime);
//            mBitMap = retr.getFrameAtTime();
            videoLength = Double.parseDouble(videoTime) / 1000.00;
            UtilsLog.e("MyUploadService---videoLength=" + videoLength);

        } catch (Exception e) {
            e.printStackTrace();
            UtilsLog.e("MyUploadService---异常错误==e=" + e.getMessage());
            videoLength = 0.00;
//            finish();
//            Toast.makeText(this, "异常错误", Toast.LENGTH_SHORT);
        }

    }

    /**
     * 没有文件夹。创建文件夹
     *
     * @param filePath
     */
    public void makeRootDirectory(String filePath) {
        UtilsLog.e("MyUploadService---makeRootDirectory=");
        File file = null;
        try {
            file = new File(filePath);
            if (!file.exists()) {
                Boolean isTrue = file.mkdir();
                UtilsLog.e("MyUploadService---istrue=" + isTrue + "");
            }
        } catch (Exception e) {

        }
    }

    /**
     * 进度条，只能是整形，所以max为1000，最少为0
     *
     * @param source
     * @return
     */
    double getProgressNum = 0.0;

    private double getProgress(String source) {
        if (source.contains("too large")) {//当文件过大的时候，会会出现 Past duration x.y too large
            UtilsLog.e("MyUploadService---too large");
            return getProgressNum;
        }
        Pattern p = Pattern.compile("00:\\d{2}:\\d{2}");
        Matcher m = p.matcher(source);
        if (m.find()) {
            //00:00:00
            String result = m.group(0);
            String temp[] = result.split(":");
            double seconds = Double.parseDouble(temp[1]) * 60 + Double.parseDouble(temp[2]);
            if (0 != videoLength) {
                getProgressNum = seconds / videoLength * 1000;
                return seconds / videoLength * 1000;
            }
            if (seconds == videoLength) {
                return 1000;
            }
        }
//        MyLog.i(TAG, "!m.find()="+getProgressNum);
        return 10000;//出现异常的时候，返回为10000
//      return 0;//出现异常的时候，显示上一个进度条
    }

    private String getFileSize(String path) {
        File f = new File(path);
        if (!f.exists()) {
            return "0 MB";
        } else {
            long size = f.length();
            return (size / 1024f) / 1024f + "MB";
        }
    }
}
